<template>
  <div class="shopcart_container" v-if="token">
    <van-space class="shopcart_wrap" direction="vertical" fill>
      <van-divider :style="{ color: '#1989fa', borderColor: '#1989fa', padding: '0 16px' }">购物车</van-divider>
      <div class="shopcart_content">
        <van-card :num="card.count" :price="card.price" desc="描述信息" :title="card.goodsName" :thumb="card.goodsImg"
          v-for="(card, index) in shopcartList" :key="card.id">
          <template #tags>
            <van-checkbox style="position: absolute; right: 0; top: 30px;" :checked="card.isChecked"
              @click="changeGoodsStatus(index)"></van-checkbox>
          </template>
          <template #footer>
            <van-button size="small" style="font-size: 20px; width: 30px;"
              @click="changeGoodsCount(index, 'cut')">-</van-button>
            <van-button size="small" style="font-size: 20px; width: 30px;"
              @click="changeGoodsCount(index, 'add')">+</van-button>
          </template>
        </van-card>
      </div>
      <van-divider :style="{ color: '#1989fa', borderColor: '#1989fa', padding: '0 16px' }"></van-divider>
      <!-- 底部 -->
      <van-submit-bar :price="totalPrice" button-text="提交订单" @submit="onSubmit"
        style="margin-bottom: 50px; --van-submit-bar-button-height:35px;">
        <van-checkbox v-model="isAllChecked">全选</van-checkbox>
      </van-submit-bar>
    </van-space>
  </div>
  <ToLogin v-else></ToLogin>
</template>

<script lang="ts">
import { defineComponent } from "vue"
export default defineComponent({
  name: 'Shopcart',
})
</script>

<script lang="ts" setup>
import { ref, computed } from 'vue'
import ToLogin from '@/components/ToLogin/index.vue'
import useShopcartStore from '@/stores/shopcart';
import { storeToRefs } from 'pinia';
import type {ShopcartData} from '@/stores/shopcart'
const shopcartStore = useShopcartStore()
const { shopcartList } = storeToRefs(shopcartStore)
const token = localStorage.getItem('token')
function onSubmit() {

}
//修改商品选中状态
function changeGoodsStatus(index: number) {
  shopcartStore.changeGoodsStatus(index)
}
//修改商品数量
function changeGoodsCount(index: number, type: string) {
  shopcartStore.changeGoodsCount(index, type)
}
//全选
const isAllChecked = computed({
  get() { 
    return shopcartList.value.every((item)=>item.isChecked)
  },
  set(newVal) { 
    shopcartStore.changeAllGoosStatus(newVal)
  }
})
//计算总价
const totalPrice = computed(()=>{
  let price =  shopcartList.value.reduce((prev:any,item:ShopcartData)=>{
    if(item.isChecked){
      prev+=item.price * item.count
    }
    return prev
  },0)
  return price*100
})
</script>

<style scoped>
.shopcart_container {
  background-color: #f4f4f4;
  padding: 20px;
}

.shopcart_wrap {
  background-color: #ffffff;
  border-radius: 10px;

}
</style>